import pandas as pd
import numpy as np
import json
import os

def generate_dynamic(db, ob_win, features):
    #choose the features
    dynamic_data = db[features].values
    #get the length of row
    data_length = dynamic_data.shape[0]
    #return the data
    for start,stop in zip(range(0, data_length-ob_win), range(ob_win, data_length)):
        yield dynamic_data[start:stop, :]


def generate_static(db, ob_win, features):
    #choose the features
    static_data = db[features].values
    #get the length of row
    data_length = static_data.shape[0]
    #return the data after ob_win time
    return static_data[ob_win-1 : data_length-1, :]

def generate_labels(db, ob_win, features):
    #choose the label feature
    label_data = db[features].values
    #get the length of row
    data_length = label_data.shape[0]
    #return the data after ob_win time
    return label_data[ob_win-1 : data_length-1, :]

#本函数返回静态数据static_data，动态数据 dynamic_datal，标签数据abel_data
def generate_data(db, ob_win, static_features, dynamic_features, label_features):
    #generate_data(df, length, static_features, dynamic_features, label_features)
    #db = 合并后的csv表格
    #ob_win = length = 15
    #static_features = config["static_features"] #null
    #dynamic_features = config["dynamic_features"]#["MAP", "SDP", "HR"]
    #label_features= config["label_features"]#["label"]
    
    grouped = db.groupby("caseid")
    #static data
    if not static_features == None: #如果static_features不为空
        print("static data...")
        #type : list
        #static_data = [list(generate_static(db[db["caseid"]==id], ob_win, static_features)) for id in db["caseid"].unique()]
        static_data = [list(generate_static(group, ob_win, static_features)) for value, group in grouped]
        #drop [] 去空值
        static_data = [sd for sd in static_data if sd != []]
        #type list to type array
        static_data = np.concatenate(static_data).astype(np.float32)
        #static_data = np.concatenate(static_data)
    else:
        static_data = None

    #label_data
    print("label data...")
    #label_data = [list(generate_labels(db[db["caseid"]==id], ob_win, label_features)) for id in db["caseid"].unique()]
    label_data = [list(generate_labels(group, ob_win, label_features)) for value, group in grouped]
    #drop [] 去空值
    label_data = [ld for ld in label_data if ld != []]
    #type list to type array
    label_data = np.concatenate(label_data).astype(np.float32)

    #dynamic data
    print("dynamic data...")
    #type : list
    #dynamic_data = [list(generate_dynamic(db[db["caseid"]==id], ob_win, dynamic_features)) for id in db["caseid"].unique()]
    dynamic_data = [list(generate_dynamic(group, ob_win, dynamic_features)) for value, group in grouped]
    #drop [] 去空值
    dynamic_data = [dd for dd in dynamic_data if dd != []]
    #type list to type array
    dynamic_data = np.concatenate(dynamic_data).astype(np.float32)

    return static_data, dynamic_data, label_data
    #return dynamic_data, label_data

def process(static, dynamic, label, pre_time,static_features):
    label = label + 100
    pre_time = pre_time + 100
    label[label == pre_time] = 1
    label[label == 100] = 0
    label[label > 1] = 2
    dynamic = np.delete(dynamic, [i for i,x in enumerate(label) if x==[2]], 0)
    if not static_features == None:
        static = np.delete(static, [i for i,x in enumerate(label) if x==[2]], 0)
    label = np.delete(label, [i for i,x in enumerate(label) if x==[2]], 0)
    return static, dynamic, label
'''
def process(dynamic, label):
    label[label == [-2]] = [2]
    label[label == [-1]] = [2]
    label[label == [3]] = [2]
    dynamic = np.delete(dynamic, [i for i,x in enumerate(label) if x==[2]], 0)
    label = np.delete(label, [i for i,x in enumerate(label) if x==[2]], 0)

    return dynamic, label
'''
def gen_data(source, d_path, c_path, pre_time, length=15):
    #source = tongji
    #d_path = "tongji/dynamic_normalization/5-bt.csv"
    #c_path = "config_bt.json"
    #pre_time = 1.0
    with open(c_path, encoding="utf-8") as config_file:#打开config_bt.json文件
        '''
        {
            "train_path": "static/train_case.csv",
            "static_features": null,
            "dynamic_features": ["MAP", "SDP", "HR"],
            "label_features": ["label"]
        }
        '''
        config = json.load(config_file)
        s_path = source + "/" + config["train_path"]#vital/static/train_case.csv
        static_features = config["static_features"] #null
        dynamic_features = config["dynamic_features"]#["MAP", "SDP", "HR"]
        label_features = config["label_features"]#["label"]
    print("reading data...")
    static_df = pd.read_csv(s_path)#tongji/static/train_case.csv
    dynamic_df = pd.read_csv(d_path)#tongji/dynamic_normalization/1-bt.csv"
    df = pd.merge(static_df, dynamic_df, how="inner", on=["caseid"])#inner内连接

    #dynamic, label = generate_data(df, length, None, dynamic_features, label_features)
    static, dynamic, label = generate_data(df, length, static_features, dynamic_features, label_features)

    #dynamic, label = process(dynamic, label)
    static, dynamic, label = process(static, dynamic, label, pre_time,static_features)

    if not static_features == None:
        d_mean = dynamic.mean(1)
        d_median = np.median(dynamic, 1)
        d_std = dynamic.std(1)
        d_min = dynamic.min(1)
        d_max = dynamic.max(1)
        #print(label.sum(), label.shape[0])
        static = np.concatenate([static, d_mean, d_median, d_std, d_min, d_max], axis=1)

    return static, dynamic, label
    #return dynamic, label
    



